(function($){
	$.dooDialog = function(){
		var pluginName = 'dooDialog';
		var set = {
			skin:'blue',
			lock:false,
			contentId:'',
			isChildNode:false,
			contentIframeSrc:'',
			title:'',
			width:200,
			height:120,
			overlay:true,
			onClose:null,
			onOpen:null,
			buttons:[],
			position:null,
			debug:false,
			cache:false,
			dragable:true,
			lang:"zh"
		};
		
		var lang = {
			'zh':{
				'note':'提示消息',
				'confirm':'确认消息',
				'ok':'确 定',
				'cancel':'取 消'
			},
			'en':{
				'note':'Note:',
				'confirm':'Confirm',
				'ok':'OK',
				'cancel':'Cancel'				
			}
		};
		
		var id_prefix      = 'dia_instance_',
			overlay_prefix = 'dia_overlay_',
			ie             = '\v'=='v',
			ie6            = !window.XMLHttpRequest,
			existent       = {},
			dia_lock_flag  = 'dia_lock';		


		function pageSize(){
			var de = document.documentElement;
			var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
			var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
			w = Math.min($('body').width(), w);
			return [w,h];
		}
		
		function getOverlay(id){
			return $('#'+overlay_prefix+id);
		}
		
		function getDia(id){
			return $('#'+id_prefix+id);
		}
		
		function titleDia(title, dia){
			$('.title', dia).html(title);	
		}
		
		function lockDia(dia){
			dia.addClass(dia_lock_flag);
			$('.lock_ico', dia).show();
			$('.close_ico', dia).hide();
		}
		
		function unlockDia(dia){
			dia.removeClass(dia_lock_flag);
			$('.lock_ico', dia).hide();
			$('.close_ico', dia).show();			
		}
		
		function isLockedDia(dia){
			return dia.hasClass(dia_lock_flag);
		}

		function dragDia(title,dialog){
			var draging = false, mouseX_1, mouseY_1, x, y, x2, y2, max_x, max_y, page_size, page_width, page_height, dia_width, dia_height;
			title.mousedown(function(e){
				draging = true;
				mouseX_1 = e.pageX;
				mouseY_1 = e.pageY;
				pos = dialog.offset();
				x = pos.left;
				y = parseInt(dialog.css('top'), 10);
				page_size = pageSize();
				page_width = page_size[0];
				page_height = page_size[1];
				dia_width = dialog.width();
				dia_height = dialog.height();
				max_x = page_width-dia_width;
				max_y = page_height-dia_height;
				
				$(document).mousemove(function(e2){					
					if(draging===false) {return;}
					y2 = y+(e2.pageY - mouseY_1);
					x2 = x+(e2.pageX - mouseX_1);
					
					if(y2<0){y2 = 0;}else if(y2>max_y){y2 = max_y;}
					if(x2<0){x2 = 0;}else if(x2>max_x){x2 = max_x;}
					
					dialog.css({
						'top' : y2,
						'left': x2
					});
					return false;//important!
				}).mouseup(function(){
					if(draging===false) {return;}
					$(document).unbind('mousemove');
					draging = false;
					return false;						
				});
			}).mouseup(function(){
				if(draging===false) {return;}
				$(document).unbind('mousemove');
				draging = false;
				return false;
			});
		}

		//这个函数先执行内置的动作，然后将执行所有onClose函数
		function closeDia(set){
			var dia = getDia(set.contentId);
			if(isLockedDia(dia) || dia.is(':hidden')){return;}
			if(set===undefined){
				alert('param set is undefined.');
				return;
			}

			//如果设置了缓存dialog，将overlay和dia隐藏，否则，还原到初始化状态。
			var overlay = getOverlay(set.contentId);
			if(set.cache){
				if(set.overlay){overlay.hide();}
				dia.hide();
			}else{
				if(set.overlay){overlay.remove();}
				if(set.isChildNode){
					$('#'+set.contentId).hide().appendTo(iframe_right.$('body'));
				}else{
					$('#'+set.contentId).hide().appendTo('body');
				}
				dia.remove();
			}

			//operate all "onClose" callback functions.
			if($.isFunction(set.onClose)){set.onClose();}
		}

		//find a btn by button name
		function getBtn(name, dia){
			return $('.btn_l:contains("'+name+'")', dia);
		}
		
		function lockBtn(btn){
			btn.addClass('lock');
		}
		
		function unlockBtn(btn){
			btn.removeClass('lock');
		}
		
		function isLockedBtn(btn){
			return btn.hasClass('lock');
		}

		/**
		 * Set the active dialog z-index
		 * @param o {number} the current z-index of clicked dialog
		 */
		function setzIndex(o){
			var max = 0;
			var all = $('.dia:visible').each(function(){				
				z = +$(this).css('z-index');
				if(z>max){max = z;}
			});
			var cur_zindex = Number(o.css('z-index'));
			o.css('z-index', max+1);	
		}

		function createBtn(btn_set, dia_set){
			
			btn_set = $.extend({}, {
				name:'button',
				event:null,
				id:'',
				extClass:'',
				lock:false,
				side:'right'
			}, btn_set);

			var btn = $('<div class="button01">'+btn_set.name+'</div>');

			if(btn_set.lock===true){
				lockBtn(btn);
			}
			
			//bind event
			btn.click(function(){
				if(isLockedBtn($(this))){return;}
				//buttons with callback
				if( $.isFunction(btn_set.event) && btn_set.event()===false ){return;}
				closeDia(dia_set);					
			}).hover(function(){
				if(isLockedBtn($(this))){return;}
				$(this).addClass('btn_l_hover');
			},function(){
				if(isLockedBtn($(this))){return;}
				$(this).removeClass('btn_l_hover');
			});
				
			if($.trim(btn_set.id)){btn[0].id=btn_set.id;}
			if($.trim(btn_set.extClass)){btn.addClass(btn_set.extClass);}
			
			return btn;
		}
		
		/*
		根据width， height， position的设置计算top和left的值，定位dia实例
		*/
		function placeDia(dia, dia_width, dia_height, page_width, page_height, position){
			var dia_top;
			var dia_left;

			if(position===null || typeof position != 'object' || ('top' in position && 'bottom' in position) || ('left' in position && 'right' in position) || (!('top' in position) && !('bottom' in position)) || (!('left' in position) && !('right' in position))){
				dia_top  = (page_height-dia_height)*0.5+$(window).scrollTop()-60; // chenxulin
				dia_left = (page_width-dia_width)*0.5;			
			}else{
				dia_top  = 'top'  in position ? position.top  : (page_height-dia_height-position.bottom-60);
				dia_left = 'left' in position ? position.left : (page_width-dia_width-position.right);
				if(dia_top<0)dia_top=0;
				dia.css({
					top:  dia_top,
					left: dia_left
				});				
			}
			
			if(dia_top<0)dia_top=0;
			dia.css({
				top:dia_top,
				left:dia_left				
			});
			
			/*
			body的高度为100%时，所有浏览器都不抖动。否则在IE6中会抖动。
			*/
			if(ie6){
				dia.css({
					top:dia_top
				});
				$(window).scroll(function(){
					dia.css('top',dia_top);
				});
			}			
		}
		
		//检查是否是百分比设置
		function isPercent(v){
			return ((typeof v === 'string') && (/%$/.test(v)===true)) ? true : false;
		}
		
		
		function openDia(options){
			var _set = $.extend({}, set, options);
			var overlay;
			
			if($.trim(_set.contentId)===''){
				alert('option: "contentId" is required.');
				return;		
			}
			
			if(getDia(_set.contentId).is(':visible')){	
				return existent[_set.contentId];
			}
	
			if($.isFunction(_set.onOpen)){ _set.onOpen(); }
			
			var old_maybe = existent[_set.contentId];
			if(typeof old_maybe==='object'){
				if(_set.lock){lockDia(old_maybe);}
				old_maybe.show();
				getOverlay(_set.contentId).show();
				return old_maybe;
			}
			
			//overlay没有用到窗口大小的计算
			if(_set.overlay){
				overlay = $('<div id="'+overlay_prefix+_set.contentId+'" class="dia_overlay" />').appendTo('body');
					overlay.height("100%");
				overlay.show();
			}

			var uid         = id_prefix + _set.contentId;
			var page_size   = pageSize();
			var page_width  = page_size[0];
			var page_height = page_size[1];
			
			var dia_width  = isPercent(_set.width)  ? page_width*parseInt(_set.width)*0.01   : parseInt(_set.width);
			var dia_height = isPercent(_set.height) ? page_height*parseInt(_set.height)*0.01 : parseInt(_set.height);			
			
			var btn_height = _set.buttons.length === 0 ? 0 : 40;
			
			var content_width = dia_width - 3;
			
			//38=25(title heigth)+1*2(box padding)+1*2(box border)+4*2(transparent border)+1(content top border)
			var content_height = dia_height - 38 - btn_height;
			
			var dialog = $('<div class="dia skin_'+_set.skin+'" id="'+uid+'" />').css({
				width:dia_width,
				height:dia_height
			}).mousedown(function(){
				setzIndex($(this));
			}).appendTo('body');
			
			
			if(_set.fixed && _set.fixed == true){
				if (ie6){ overlay.height($('body').height());}	
			}else{
				dialog.css("position","absolute");
			}
			
			
			setzIndex(dialog);
	
			/*
			var edge = $('<div class="edge" />').css({
				width:dia_width,
				height:dia_height
			}).appendTo(dialog);
			*/
	
			//var box = $('<div class="box" />').css({
			var box = $('<div class="divline" />').css({
				width :dia_width - 3,
				height:dia_height - 12
			}).appendTo(dialog);
	
			var head = "<table width='100%' border='0' cellspacing='0' cellpadding='0' class='layer01'><tr><td class='headb'>"+_set.title+"</td></tr></table>";
		
			var title = $('<div unselectable="on">'+head+'</div>').appendTo(box);
	
			var close_ico = $('<div class="close_ico" />').click(function(){
				if(!isLockedDia(dialog)){ closeDia(_set); }
			}).appendTo(dialog);
			
			var lock_ico = $('<div class="lock_ico" />').appendTo(dialog);
			
			if(_set.lock){lockDia(dialog);}else{unlockDia(dialog);}

			if (_set.isChildNode){
				if(iframe_right.$('#'+_set.contentId).length == 0){
					alert('option: "contentId" is not object.');
					return false;
				}else{
					var content = $('<div class="content" />').css({
						width:content_width,
						height:content_height
					}).append(iframe_right.$('#'+_set.contentId).show()).appendTo(box);
				}
			}else{
				if($('#'+_set.contentId).length == 0){
					alert('option: "contentId" is not object.');
					return false;
				}else{
					var content = $('<div class="content" />').css({
						width:content_width,
						height:content_height
					}).append($('#'+_set.contentId).show()).appendTo(box);
				}
			}
	
			//add buttons
			var btns_array = _set.buttons;
			var i = btns_array.length;
			
			if(i){
				var	btns = $('<div class="btns" />').appendTo(box);
				while(i--){
					createBtn(btns_array[i], _set).appendTo(btns);
				}				
			}

			if(_set.dragable){
				dragDia(title, dialog);
				title.css('cursor','move');
			}
			
			placeDia(dialog, dia_width, dia_height, page_width, page_height, _set.position);
			
			$(window).resize(function(){
				if(!$('div[id^='+id_prefix+']').length){return;}
				page_size      = pageSize();
				page_width     = page_size[0];
				page_height    = page_size[1];
				dia_width      = isPercent(_set.width) ? page_width*parseInt(_set.width)*0.01   : parseInt(_set.width);
				dia_height     = isPercent(_set.height) ? page_height*parseInt(_set.height)*0.01 : parseInt(_set.height);
				content_width  = dia_width - 3;
				content_height = dia_height - 38 - btn_height;
				
				dialog.css({width:dia_width, height:dia_height});
				//edge.css({width:dia_width, height:dia_height});
				box.css({width:dia_width-3, height:dia_height-12});
				content.css({width:content_width, height:content_height});

				placeDia(dialog, dia_width, dia_height, page_width, page_height, _set.position);
			});			
			
			//add APIs
			dialog = $.extend(dialog,{
				lock:function(){
					lockDia(dialog);
				},
				unlock:function(){
					unlockDia(dialog);
				},
				lockBtn:function(name){
					lockBtn(getBtn(name, dialog));
				},
				unlockBtn:function(name){
					unlockBtn(getBtn(name, dialog));
				},
				title:function(title){
					titleDia(title, dialog);
				},
				close:function(){
					closeDia(_set);
				}
			});
	
			//save a cache to indicate the instance has been existed.
			if(_set.cache){
				existent[_set.contentId] = dialog;		
			}

			//return instance
			return dialog;			
		}	
		

		return {
			open:function(set){
				return openDia(set);
			},
			openIframe:function(i_set){
				//the alert instance and it's overlay will be removed by uid later
				var uid = 'iframe_'+ i_set.name || new Date().getTime();
				var iframeContent = $('<iframe id="'+uid+'" src="'+i_set.src+'" height="100%" width="100%" frameborder="0" name="'+i_set.name+'"></iframe>').css({
					display:'none'
				}).appendTo('body');
				
				return openDia($.extend({}, set, {
					skin:      i_set.skin,
					contentId: uid,
					title:     i_set.title,
					width:     i_set.width,
					height:    i_set.height,
					overlay:   i_set.overlay,
					onOpen:    i_set.onOpen,
					onClose:   function(){
						iframeContent.remove();
						if($.isFunction(i_set.onClose)){i_set.onClose();}
					},
					position:  i_set.position,
					buttons:   i_set.buttons,
					debug:     i_set.debug,
					cache:     false,
					dragable:  i_set.dragable
				}));				
			},
			/*
			@param
				html:    the words placed in the alert dialog
				callback:a function that will be fired when dialog is closed
			*/
			alert:function(html, callback, l/*language*/, s/*skin*/){
				//the alert instance and it's overlay will be removed by uid later
				var uid = 'alert_'+new Date().getTime();
				var alertContent = $('<div id="'+uid+'" />').css({
					display:'none',
					padding:'10px'
				}).html(html).appendTo('body');
				l = l || 'zh';
				s = s || 'default';
				openDia($.extend({}, set, {
					skin:s,
					contentId:uid,
					title:lang[l].note,
					width:280,
					overlay:true,
					onClose:function(){
						alertContent.remove();
						if($.isFunction(callback)){callback();}
					},
					buttons:[{
						name:lang[l].ok
					}],
					cache:false
				}));		
			},
			/*
			@param
				html:    the words placed in the confirm dialog
				callback:a function that will be fired when  "OK" button is clicked
			*/
			confirm:function(html, callback, l/*language*/, s/*skin*/){
				//the confirm instance and it's overlay will be removed by uid later
				var uid = 'confirm_'+new Date().getTime();
				var confirmContent = $('<div id="'+uid+'" />').css({
					display:'none',
					padding:'10px'
				}).html(html).appendTo('body');
				l = l || 'zh';
				s = s || 'default';
				openDia($.extend({}, set, {
					skin:s,
					width:250,
					height:130,
					contentId:uid,
					title:lang[l].confirm,
					overlay:true,
					onClose:function(){
						confirmContent.remove();
					},
					buttons:[{						
						name:lang[l].ok,
						event:callback
					},{
						name:lang[l].cancel
					}],
					cache:false
				}));
				return false;
			}
		};
	}();
})(jQuery);


(function($){
	$.simpleTip = function(options){
		var settings = {}
		settings = $.extend({},settings,options);
		var ie='\v'=='v';
		var ie6 = ie && !window.XMLHttpRequest;
		var tipStack = {
			length : 0
		}
		var getTemplate = function(type,content,timestamp){
			return $('<div id="'+timestamp+'" style="margin:0 auto;"><div class="SimpleTipWrapper '+type+'">\
						<div class="SimpleTipContent">'+content+'</div>\
						<a class="SimpleTipClose" href="#" rel="'+timestamp+'">X</a>\
					 </div></div>');
		}
		// Close button
		$('.SimpleTipClose').live('click',function(){
			close($(this).attr("rel"));
			return false;
		});
		function close(id){
			var tip = $('#'+id);
			delete tipStack[id];
			tipStack.length--;
			tip.animate({
				height : 0,
				opacity : 0
			},300,function(){
				tip.remove();
				setPos();
			});
		}
		//remove all the tip instance
		function clear(){
			eachStack(function(i){
				$('#'+i).slideUp(300,function(){
					$(this).remove();
				});
			});
			tipStack={
				length : 0
			}
			debug.viewStack(true);
		}
		var wrapper = $('<div class="simpleTipContainer"></div>');
		$('body').append(wrapper);
		function open(opt){
			var set = $.extend({},{
				type : "info",
				autoClose : false,
				closeAncestor : false,
				timeOut : 4000
			},opt);
			if (!$.trim(opt.content).length) {
				throw new Error("Error on globalTip : Please make sure that the content is not empty.");
			}			
			var timestamp = new Date().getTime();
			var tpl = getTemplate(opt.type,opt.content,timestamp);
			tipStack[timestamp] = tpl;
			tipStack.length++;
			wrapper.append(tpl);
			tpl.css("float","left");
			tpl.css("width",tpl.width());
			tpl.css("float","none");
			setPos(tpl);
			// if a tip was opend before
			if(opt.closeAncestor && tipStack.length > 1){
				eachStack(function(id){
					if (id != timestamp) {
						close(id);
					}
				});
			}
			tpl.slideDown();
			if(set.autoClose){
				setTimeout(function(){
					close(timestamp);
				},set.timeOut);
			}
			$(window).resize(function(){
				setPos(tpl);
			});
			if(ie6){
				$(window).scroll(function(){
					setPos(tpl);
				});
			}
			debug.viewStack(false);
		}
		function setPos(tpl){
			var width = wrapper.width();
			if(width === 0){
				//wrapper is empty
				wrapper.css('left','');
				return false;
			}
			if(ie6){
				wrapper.css({
					left :  $(window).width()/2 - width/2,
					top : $(document).scrollTop()
				});
			}else{
				wrapper.css('left', $(window).width()/2 - width/2);
			}
		}
		function eachStack(fn){
			for(var i in tipStack){
				if(i === 'length') continue;
				fn(i,tipStack[i]);
			}
		}
		var debug = {
			viewStack : function(clear){

			}
		}
		return {
			open : open,
			clear : clear
		}
	}
	var init = $.simpleTip();
	$.simpleTip.open = function(opt){
		init.open(opt);
	}
	$.simpleTip.clear = function(){
		init.clear();
	}
})(jQuery);

var TX = TX || {};
TX.tip = function(type,content,autoClose,closeAncestor){
	$.simpleTip.open({
		type : type,
		content : content,
		autoClose : autoClose,
		closeAncestor : closeAncestor
	});
}
TX.clearTip = function(){
	$.simpleTip.clear();
}
TX.scrollTo = function(ele,offset,ext){
    $('html,body').animate({
        scrollTop : ele.offset().top - offset
    },800,function(){
		if(ext && ext.after){
			ext.after();
		}
	});
}
TX.alert = function(content){
	$.dooDialog.alert(content);
}
TX.confirm = function(content,fn){
	$.dooDialog.confirm(content,fn);
}
TX.loader = function(path){
	for(var i = 0 ; i < path.length ; i++){
		var type = path[i].match(/\.(\w+)/g);
		type = RegExp.lastMatch.replace(/\./,"");
		if(type === "js" || type === "css"){
			var head = document.getElementsByTagName("head")[0];
			if(type === "js"){
				// script
				var node = document.createElement("script");
				node.type = "text/javascript";
				node.src = path[i];
			}else{
				// stylesheet
				var node = document.createElement("link");
				node.type = "text/css";
				node.href = path[i];
			}
			head.appendChild(node);
		}else{
			// Images
			var image = new Image();
			image.src = path[i];
		}
	}
}
